#include"test.hpp"
#include"LockGuard.hpp"
using namespace std;
class ThreadData
{
public:
ThreadData(const string &name,pthread_mutex_t*mutex)
:_threadname(name)
,_mutex(mutex)
{}

string _threadname;
pthread_mutex_t*_mutex;
};

string GetThreadName()
{
    static int number=1;
    char name[64];
    snprintf(name,sizeof name,"Thread - %d",number++);
    return name;
}
void print(int num)
{
    while(num--)
    {
    cout<<"hello world"<<num<<endl;
    sleep(1);
    }
}
int ticket=10000;
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;//全局的锁

void GetTicket(ThreadData*td)
{
    while(true)
    {
        pthread_mutex_lock(td->_mutex);
        if(ticket>0)
        {
            usleep(1000);
            printf("%s get a ticket %d\n",td->_threadname.c_str(),ticket--);
            pthread_mutex_unlock(td->_mutex);
        }
        else
        {
        pthread_mutex_unlock(td->_mutex);
        break;
       
        }
    }
}

int main()
{
    int num=5;
    //vector<Thread<int>> Threads;
    pthread_mutex_t mutex;
    pthread_mutex_init(&mutex,nullptr);
    string name1=GetThreadName();
    string name2=GetThreadName();
    string name3=GetThreadName();
    string name4=GetThreadName();
    ThreadData*td1=new ThreadData(name1,&mutex);
    ThreadData*td2=new ThreadData(name2,&mutex);
    ThreadData*td3=new ThreadData(name3,&mutex);
    ThreadData*td4=new ThreadData(name4,&mutex);


    Thread<ThreadData*> t1(GetTicket,name1,td1);
    Thread<ThreadData*> t2(GetTicket,name2,td2);
    Thread<ThreadData*> t3(GetTicket,name3,td3);
    Thread<ThreadData*> t4(GetTicket,name4,td4);

    t1.Start();
    t2.Start();
    t3.Start();
    t4.Start();

    t1.Join();
    t2.Join();
    t3.Join();
    t4.Join();
    pthread_mutex_destroy(&mutex);
    delete td1;
    delete td2;
    delete td3;
    delete td4;

    return 0;
}